home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 21 / AACD 21.iso / AACD / Utilities / Ghostscript / src / gdevps.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-01-01  |  42.5 KB  |  1,405 lines

  1. /* Copyright (C) 1997, 2000 Aladdin Enterprises.  All rights reserved.
  2.   
  3.   This file is part of AFPL Ghostscript.
  4.   
  5.   AFPL Ghostscript is distributed with NO WARRANTY OF ANY KIND.  No author or
  6.   distributor accepts any responsibility for the consequences of using it, or
  7.   for whether it serves any particular purpose or works at all, unless he or
  8.   she says so in writing.  Refer to the Aladdin Free Public License (the
  9.   "License") for full details.
  10.   
  11.   Every copy of AFPL Ghostscript must include a copy of the License, normally
  12.   in a plain ASCII text file named PUBLIC.  The License grants you the right
  13.   to copy, modify and redistribute AFPL Ghostscript, but only under certain
  14.   conditions described in the License.  Among other things, the License
  15.   requires that the copyright notice and this notice be preserved on all
  16.   copies.
  17. */
  18.  
  19. /*$Id: gdevps.c,v 1.12 2000/09/19 19:00:21 lpd Exp $ */
  20. /* PostScript-writing driver */
  21. #include "math_.h"
  22. #include "memory_.h"
  23. #include "time_.h"
  24. #include "gx.h"
  25. #include "gserrors.h"
  26. #include "gscdefs.h"
  27. #include "gsmatrix.h"        /* for gsiparam.h */
  28. #include "gsiparam.h"
  29. #include "gsline.h"
  30. #include "gsparam.h"
  31. #include "gxdevice.h"
  32. #include "gscspace.h"
  33. #include "gxdcolor.h"
  34. #include "gxpath.h"
  35. #include "spprint.h"
  36. #include "strimpl.h"
  37. #include "sstring.h"
  38. #include "sa85x.h"
  39. #include "gdevpsdf.h"
  40. #include "gdevpsu.h"
  41.  
  42. /* Current ProcSet version */
  43. #define PSWRITE_PROCSET_VERSION 1
  44.  
  45. /* ---------------- Device definition ---------------- */
  46.  
  47. /* Device procedures */
  48. private dev_proc_open_device(psw_open);
  49. private dev_proc_output_page(psw_output_page);
  50. private dev_proc_close_device(psw_close);
  51. private dev_proc_copy_mono(psw_copy_mono);
  52. private dev_proc_copy_color(psw_copy_color);
  53. private dev_proc_put_params(psw_put_params);
  54. private dev_proc_get_params(psw_get_params);
  55. private dev_proc_fill_path(psw_fill_path);
  56. private dev_proc_stroke_path(psw_stroke_path);
  57. private dev_proc_fill_mask(psw_fill_mask);
  58. private dev_proc_begin_image(psw_begin_image);
  59.  
  60. #define X_DPI 720
  61. #define Y_DPI 720
  62.  
  63. typedef struct psw_path_state_s {
  64.     int num_points;        /* # of points since last non-lineto */
  65.     int move;            /* 1 iff last non-lineto was moveto, else 0 */
  66.     gs_point dprev[2];        /* line deltas before previous point, */
  67.                 /* if num_points - move >= 2 */
  68. } psw_path_state_t;
  69.  
  70. typedef struct psw_image_params_s {
  71.     gx_bitmap_id id;
  72.     ushort width, height;
  73. } psw_image_params_t;
  74.  
  75. typedef struct gx_device_pswrite_s {
  76.     gx_device_psdf_common;
  77.     /* LanguageLevel in pswrite_common is settable. */
  78.     gx_device_pswrite_common_t pswrite_common;
  79. #define LanguageLevel_default 2.0
  80. #define psdf_version_default psdf_version_level2
  81.     /* End of parameters */
  82.     bool first_page;
  83.     psdf_binary_writer *image_writer;
  84. #define image_stream image_writer->strm
  85. #define image_cache_size 197
  86. #define image_cache_reprobe_step 121
  87.     psw_image_params_t image_cache[image_cache_size];
  88.     bool cache_toggle;
  89.     /* Temporary state while writing a path */
  90.     psw_path_state_t path_state;
  91. } gx_device_pswrite;
  92.  
  93. /* GC descriptor and procedures */
  94. gs_private_st_suffix_add1_final(st_device_pswrite, gx_device_pswrite,
  95.                 "gx_device_pswrite", device_pswrite_enum_ptrs,
  96.                 device_pswrite_reloc_ptrs, gx_device_finalize,
  97.                 st_device_psdf, image_writer);
  98.  
  99. #define psw_procs\
  100.     {    psw_open,\
  101.         gx_upright_get_initial_matrix,\
  102.         NULL,            /* sync_output */\
  103.         psw_output_page,\
  104.         psw_close,\
  105.         gx_default_rgb_map_rgb_color,\
  106.         gx_default_rgb_map_color_rgb,\
  107.         gdev_vector_fill_rectangle,\
  108.         NULL,            /* tile_rectangle */\
  109.         psw_copy_mono,\
  110.         psw_copy_color,\
  111.         NULL,            /* draw_line */\
  112.         NULL,            /* get_bits */\
  113.         psw_get_params,\
  114.         psw_put_params,\
  115.         NULL,            /* map_cmyk_color */\
  116.         NULL,            /* get_xfont_procs */\
  117.         NULL,            /* get_xfont_device */\
  118.         NULL,            /* map_rgb_alpha_color */\
  119.         gx_page_device_get_page_device,\
  120.         NULL,            /* get_alpha_bits */\
  121.         NULL,            /* copy_alpha */\
  122.         NULL,            /* get_band */\
  123.         NULL,            /* copy_rop */\
  124.         psw_fill_path,\
  125.         psw_stroke_path,\
  126.         psw_fill_mask,\
  127.         gdev_vector_fill_trapezoid,\
  128.         gdev_vector_fill_parallelogram,\
  129.         gdev_vector_fill_triangle,\
  130.         NULL /****** WRONG ******/,    /* draw_thin_line */\
  131.         psw_begin_image,\
  132.         NULL,            /* image_data */\
  133.         NULL,            /* end_image */\
  134.         NULL,            /* strip_tile_rectangle */\
  135.         NULL/******psw_strip_copy_rop******/\
  136.     }
  137.  
  138. const gx_device_pswrite gs_pswrite_device = {
  139.     std_device_dci_type_body(gx_device_pswrite, 0, "pswrite",
  140.                  &st_device_pswrite,
  141.                  DEFAULT_WIDTH_10THS * X_DPI / 10,
  142.                  DEFAULT_HEIGHT_10THS * Y_DPI / 10,
  143.                  X_DPI, Y_DPI, 3, 24, 255, 255, 256, 256),
  144.     psw_procs,
  145.     psdf_initial_values(psdf_version_default, 1 /*true */ ),    /* (ASCII85EncodePages) */
  146.     PSWRITE_COMMON_VALUES(LanguageLevel_default, /* LanguageLevel */
  147.               0 /*false*/, /* ProduceEPS */
  148.               PSWRITE_PROCSET_VERSION /* ProcSet_version */)
  149. };
  150.  
  151. const gx_device_pswrite gs_epswrite_device = {
  152.     std_device_dci_type_body(gx_device_pswrite, 0, "epswrite",
  153.                  &st_device_pswrite,
  154.                  DEFAULT_WIDTH_10THS * X_DPI / 10,
  155.                  DEFAULT_HEIGHT_10THS * Y_DPI / 10,
  156.                  X_DPI, Y_DPI, 3, 24, 255, 255, 256, 256),
  157.     psw_procs,
  158.     psdf_initial_values(psdf_version_default, 1 /*true */ ),    /* (ASCII85EncodePages) */
  159.     PSWRITE_COMMON_VALUES(LanguageLevel_default, /* LanguageLevel */
  160.               1 /*true*/, /* ProduceEPS */
  161.               PSWRITE_PROCSET_VERSION /* ProcSet_version */)
  162. };
  163.  
  164. /* Vector device implementation */
  165. private int
  166.     psw_beginpage(P1(gx_device_vector * vdev)),
  167.     psw_setcolors(P2(gx_device_vector * vdev, const gx_drawing_color * pdc)),
  168.     psw_dorect(P6(gx_device_vector * vdev, fixed x0, fixed y0, fixed x1,
  169.           fixed y1, gx_path_type_t type)),
  170.     psw_beginpath(P2(gx_device_vector * vdev, gx_path_type_t type)),
  171.     psw_moveto(P6(gx_device_vector * vdev, floatp x0, floatp y0,
  172.           floatp x, floatp y, gx_path_type_t type)),
  173.     psw_lineto(P6(gx_device_vector * vdev, floatp x0, floatp y0,
  174.           floatp x, floatp y, gx_path_type_t type)),
  175.     psw_curveto(P10(gx_device_vector * vdev, floatp x0, floatp y0,
  176.             floatp x1, floatp y1, floatp x2, floatp y2,
  177.             floatp x3, floatp y3, gx_path_type_t type)),
  178.     psw_closepath(P6(gx_device_vector * vdev, floatp x0, floatp y0,
  179.              floatp x_start, floatp y_start, gx_path_type_t type)),
  180.     psw_endpath(P2(gx_device_vector * vdev, gx_path_type_t type));
  181. private const gx_device_vector_procs psw_vector_procs = {
  182.     /* Page management */
  183.     psw_beginpage,
  184.     /* Imager state */
  185.     psdf_setlinewidth,
  186.     psdf_setlinecap,
  187.     psdf_setlinejoin,
  188.     psdf_setmiterlimit,
  189.     psdf_setdash,
  190.     psdf_setflat,
  191.     psdf_setlogop,
  192.     /* Other state */
  193.     psw_setcolors,        /* fill & stroke colors are the same */
  194.     psw_setcolors,
  195.     /* Paths */
  196.     psdf_dopath,
  197.     psw_dorect,
  198.     psw_beginpath,
  199.     psw_moveto,
  200.     psw_lineto,
  201.     psw_curveto,
  202.     psw_closepath,
  203.     psw_endpath
  204. };
  205.  
  206. /* ---------------- File header ---------------- */
  207.  
  208. /*
  209.  * NOTE: Increment PSWRITE_PROCSET_VERSION (above) whenever the following
  210.  * definitions change.
  211.  */
  212.  
  213. private const char *const psw_procset[] = {
  214.     "/!{bind def}bind def/#{load def}!/N/counttomark #",
  215.     /* <rbyte> <gbyte> <bbyte> rG - */
  216.     /* <graybyte> G - */
  217.  "/rG{3{3 -1 roll 255 div}repeat setrgbcolor}!/G{255 div setgray}!/K{0 G}!",
  218.     /* <bbyte> <rgbyte> r6 - */
  219.     /* <gbyte> <rbbyte> r5 - */
  220.     /* <rbyte> <gbbyte> r3 - */
  221.     "/r6{dup 3 -1 roll rG}!/r5{dup 3 1 roll rG}!/r3{dup rG}!",
  222.     "/w/setlinewidth #/J/setlinecap #",
  223.     "/j/setlinejoin #/M/setmiterlimit #/d/setdash #/i/setflat #",
  224.     "/m/moveto #/l/lineto #/c/rcurveto #/h{p closepath}!/H{P closepath}!",
  225.     /* <dx> lx - */
  226.     /* <dy> ly - */
  227.     /* <dx2> <dy2> <dx3> <dy3> v - */
  228.     /* <dx1> <dy1> <dx2> <dy2> y - */
  229.     "/lx{0 rlineto}!/ly{0 exch rlineto}!/v{0 0 6 2 roll c}!/y{2 copy c}!",
  230.     /* <x> <y> <dx> <dy> re - */
  231.     "/re{4 -2 roll m exch dup lx exch ly neg lx h}!",
  232.     /* <x> <y> <a> <b> ^ <x> <y> <a> <b> <-x> <-y> */
  233.     "/^{3 index neg 3 index neg}!",
  234.     /* <x> <y> <dx1> <dy1> ... <dxn> <dyn> P - */
  235.     "/P{N 0 gt{N -2 roll moveto p}if}!",
  236.     /* <dx1> <dy1> ... <dxn> <dyn> p - */
  237.     "/p{N 2 idiv{N -2 roll rlineto}repeat}!",
  238.     "/f{P fill}!/f*{P eofill}!/s{H stroke}!/S{P stroke}!",
  239.     "/q/gsave #/Q/grestore #/rf{re fill}!",
  240.     "/Y{P clip newpath}!/Y*{P eoclip newpath}!/rY{re Y}!",
  241.     /* <w> <h> <name> <data> <?> |= <w> <h> <data> */
  242.     "/|={pop exch 4 1 roll 3 array astore cvx exch 1 index def exec}!",
  243.     /* <w> <h> <name> <length> <src> | <w> <h> <data> */
  244.     "/|{exch string readstring |=}!",
  245.     /* <w> <?> <name> (<length>|) + <w> <?> <name> <length> */
  246.     "/+{dup type/nametype eq{2 index 7 add -3 bitshift 2 index mul}if}!",
  247.     /* <w> <h> <name> (<length>|) $ <w> <h> <data> */
  248.     "/@/currentfile #/${+ @ |}!",
  249.     /* <file> <nbytes> <ncomp> B <proc_1> ... <proc_ncomp> true */
  250.     "/B{{2 copy string{readstring pop}aload pop 4 array astore cvx",
  251.     "3 1 roll}repeat pop pop true}!",
  252.     /* <x> <y> <w> <h> <bpc/inv> <src> Ix <w> <h> <bps/inv> <mtx> <src> */
  253.     "/Ix{[1 0 0 1 11 -2 roll exch neg exch neg]exch}!",
  254.     /* <x> <y> <h> <src> , - */
  255.     /* <x> <y> <h> <src> If - */
  256.     /* <x> <y> <h> <src> I - */
  257. "/,{true exch Ix imagemask}!/If{false exch Ix imagemask}!/I{exch Ix image}!",
  258.     0
  259. };
  260.  
  261. private const char *const psw_1_procset[] = {
  262.     0
  263. };
  264.  
  265. private const char *const psw_1_x_procset[] = {
  266.     /* <w> <h> <name> <length> <src> |X <w> <h> <data> */
  267.     /* <w> <h> <name> (<length>|) $X <w> <h> <data> */
  268.     "/|X{exch string readhexstring |=}!/$X{+ @ |X}!",
  269.     /* - @X <hexsrc> */
  270.     "/@X{{currentfile ( ) readhexstring pop}}!",
  271.     0
  272. };
  273.  
  274. private const char *const psw_1_5_procset[] = {
  275.     /* <x> <y> <w> <h> <src> <bpc> Ic - */
  276.     "/Ic{exch Ix false 3 colorimage}!",
  277.     0
  278. };
  279.  
  280. private const char *const psw_2_procset[] = {
  281.     /* <src> <w> <h> -mark- ... F <g4src> */
  282.     /* <src> <w> <h> FX <g4src> */
  283.     "/F{/Columns counttomark 3 add -2 roll/Rows exch/K -1/BlackIs1 true>>",
  284.     "/CCITTFaxDecode filter}!/FX{<</EndOfBlock false F}!",
  285.     /* <src> X <a85src> */
  286.     /* - @X <a85src> */
  287.     /* <w> <h> <src> /&2 <w> <h> <src> <w> <h> */
  288.     "/X{/ASCII85Decode filter}!/@X{@ X}!/&2{2 index 2 index}!",
  289.     /* <w> <h> @F <w> <h> <g4src> */
  290.     /* <w> <h> @C <w> <h> <g4a85src> */
  291.     "/@F{@ &2<<F}!/@C{@X &2 FX}!",
  292.     /* <w> <h> <name> (<length>|) $X <w> <h> <data> */
  293.     /* <w> <h> <?> <?> <src> &4 <w> <h> <?> <?> <src> <w> <h> */
  294.     /* <w> <h> <name> (<length>|) $F <w> <h> <data> */
  295.     /* <w> <h> <name> (<length>|) $C <w> <h> <data> */
  296.     "/$X{+ @X |}!/&4{4 index 4 index}!/$F{+ @ &4<<F |}!/$C{+ @X &4 FX |}!",
  297.     /* <w> <h> <bpc> <matrix> <decode> <interpolate> <src>IC - */
  298.     "/IC{3 1 roll 10 dict begin 1{/ImageType/Interpolate/Decode/DataSource",
  299.     "/ImageMatrix/BitsPerComponent/Height/Width}{exch def}forall",
  300.     "currentdict end image}!",
  301.     0
  302. };
  303.  
  304. /* ---------------- Utilities ---------------- */
  305.  
  306. /*
  307.  * Output the file header.  This must write to a file, not a stream,
  308.  * because it may be called during finalization.
  309.  */
  310. private int
  311. psw_begin_file(gx_device_pswrite *pdev, const gs_rect *pbbox)
  312. {
  313.     FILE *f = pdev->file;
  314.  
  315.     psw_begin_file_header(f, (gx_device *)pdev, pbbox,
  316.               &pdev->pswrite_common,
  317.               pdev->params.ASCII85EncodePages);
  318.     psw_print_lines(f, psw_procset);
  319.     if (pdev->pswrite_common.LanguageLevel < 1.5) {
  320.     psw_print_lines(f, psw_1_x_procset);
  321.     psw_print_lines(f, psw_1_procset);
  322.     } else if (pdev->pswrite_common.LanguageLevel > 1.5) {
  323.     psw_print_lines(f, psw_1_5_procset);
  324.     psw_print_lines(f, psw_2_procset);
  325.     } else {
  326.     psw_print_lines(f, psw_1_x_procset);
  327.     psw_print_lines(f, psw_1_5_procset);
  328.     }
  329.     psw_end_file_header(f);
  330.     return 0;
  331. }
  332.  
  333. /* Reset the image cache. */
  334. private void
  335. image_cache_reset(gx_device_pswrite * pdev)
  336. {
  337.     int i;
  338.  
  339.     for (i = 0; i < image_cache_size; ++i)
  340.     pdev->image_cache[i].id = gx_no_bitmap_id;
  341.     pdev->cache_toggle = false;
  342. }
  343.  
  344. /* Look up or enter image parameters in the cache. */
  345. /* Return -1 if the key is not in the cache, or its index. */
  346. /* If id is gx_no_bitmap_id or enter is false, do not enter it. */
  347. private int
  348. image_cache_lookup(gx_device_pswrite * pdev, gx_bitmap_id id,
  349.            int width, int height, bool enter)
  350. {
  351.     int i1, i2;
  352.     psw_image_params_t *pip1;
  353.     psw_image_params_t *pip2;
  354.  
  355.     if (id == gx_no_bitmap_id)
  356.     return -1;
  357.     i1 = id % image_cache_size;
  358.     pip1 = &pdev->image_cache[i1];
  359.     if (pip1->id == id && pip1->width == width && pip1->height == height) {
  360.     return i1;
  361.     }
  362.     i2 = (i1 + image_cache_reprobe_step) % image_cache_size;
  363.     pip2 = &pdev->image_cache[i2];
  364.     if (pip2->id == id && pip2->width == width && pip2->height == height) {
  365.     return i2;
  366.     }
  367.     if (enter) {
  368.     int i = ((pdev->cache_toggle = !pdev->cache_toggle) ? i2 : i1);
  369.     psw_image_params_t *pip = &pdev->image_cache[i];
  370.  
  371.     pip->id = id, pip->width = width, pip->height = height;
  372.     return i;
  373.     }
  374.     return -1;
  375. }
  376.  
  377. /*
  378.  * Prepare the encoding stream for image data.
  379.  * Return 1 if using ASCII (Hex or 85) encoding, 0 if binary.
  380.  */
  381. private int
  382. psw_image_stream_setup(gx_device_pswrite * pdev, bool binary_ok)
  383. {
  384.     int code;
  385.     bool save = pdev->binary_ok;
  386.  
  387.     if (pdev->pswrite_common.LanguageLevel >= 2 || binary_ok) {
  388.     pdev->binary_ok = binary_ok;
  389.     code = psdf_begin_binary((gx_device_psdf *)pdev, pdev->image_writer);
  390.     } else {
  391.     /* LanguageLevel 1, binary not OK.  Use ASCIIHex encoding. */
  392.     pdev->binary_ok = true;
  393.     code = psdf_begin_binary((gx_device_psdf *)pdev, pdev->image_writer);
  394.     if (code >= 0) {
  395.         stream_state *st =
  396.         s_alloc_state(pdev->v_memory, s_AXE_template.stype,
  397.                   "psw_image_stream_setup");
  398.  
  399.         if (st == 0)
  400.         code = gs_note_error(gs_error_VMerror);
  401.         else {
  402.         code = psdf_encode_binary(pdev->image_writer,
  403.                       &s_AXE_template, st);
  404.         if (code >= 0)
  405.             ((stream_AXE_state *)st)->EndOfData = false; /* no > */
  406.         }
  407.     }
  408.     }
  409.     pdev->binary_ok = save;
  410.     return (code < 0 ? code : !binary_ok);
  411. }
  412.  
  413. /* Clean up after writing an image. */
  414. private void
  415. psw_image_cleanup(gx_device_pswrite * pdev)
  416. {
  417.     if (pdev->image_stream != 0) {
  418.     psdf_end_binary(pdev->image_writer);
  419.     memset(pdev->image_writer, 0, sizeof(*pdev->image_writer));
  420.     }
  421. }
  422.  
  423. /* Write data for an image.  Assumes width > 0, height > 0. */
  424. private void
  425. psw_put_bits(stream * s, const byte * data, int data_x_bit, uint raster,
  426.          uint width_bits, int height)
  427. {
  428.     const byte *row = data + (data_x_bit >> 3);
  429.     int shift = data_x_bit & 7;
  430.     int y;
  431.  
  432.     for (y = 0; y < height; ++y, row += raster)
  433.     if (shift == 0)
  434.         pwrite(s, row, (width_bits + 7) >> 3);
  435.     else {
  436.         const byte *src = row;
  437.         int wleft = width_bits;
  438.         int cshift = 8 - shift;
  439.  
  440.         for (; wleft + shift > 8; ++src, wleft -= 8)
  441.         pputc(s, (*src << shift) + (src[1] >> cshift));
  442.         if (wleft > 0)
  443.         pputc(s, (*src << shift) & (byte)(0xff00 >> wleft));
  444.     }
  445. }
  446. private int
  447. psw_put_image_bits(gx_device_pswrite *pdev, const char *op,
  448.            const byte * data, int data_x, uint raster,
  449.            int width, int height, int depth)
  450. {
  451.     pprints1(pdev->strm, "%s\n", op);
  452.     psw_put_bits(pdev->image_stream, data, data_x * depth, raster,
  453.          width * depth, height);
  454.     psw_image_cleanup(pdev);
  455.     return 0;
  456. }
  457. private int
  458. psw_put_image(gx_device_pswrite *pdev, const char *op, int encode,
  459.           const byte * data, int data_x, uint raster,
  460.           int width, int height, int depth)
  461. {
  462.     int code = psw_image_stream_setup(pdev, !(encode & 1));
  463.  
  464.     if (code < 0)
  465.     return code;
  466.     if (encode & 2) {
  467.     code = psdf_CFE_binary(pdev->image_writer, width, height, false);
  468.     if (code < 0)
  469.         return code;
  470.     }
  471.     return psw_put_image_bits(pdev, op, data, data_x, raster,
  472.                   width, height, depth);
  473. }
  474. private int
  475. psw_image_write(gx_device_pswrite * pdev, const char *imagestr,
  476.         const byte * data, int data_x, uint raster, gx_bitmap_id id,
  477.         int x, int y, int width, int height, int depth)
  478. {
  479.     stream *s = gdev_vector_stream((gx_device_vector *) pdev);
  480.     uint width_bits = width * depth;
  481.     int index = image_cache_lookup(pdev, id, width_bits, height, false);
  482.     char str[40];
  483.     char endstr[20];
  484.     int code, encode;
  485.     const char *op;
  486.  
  487.     if (index >= 0) {
  488.     sprintf(str, "%d%c", index / 26, index % 26 + 'A');
  489.     pprintd2(s, "%d %d ", x, y);
  490.     pprints2(s, "%s %s\n", str, imagestr);
  491.     return 0;
  492.     }
  493.     pprintd4(s, "%d %d %d %d ", x, y, width, height);
  494.     encode = !pdev->binary_ok;
  495.     if (depth == 1 && width > 16 && pdev->pswrite_common.LanguageLevel >= 2) {
  496.     /*
  497.      * We should really look at the statistics of the image before
  498.      * committing to using G4 encoding....
  499.      */
  500.     encode += 2;
  501.     }
  502.     if (id == gx_no_bitmap_id || width_bits * (ulong) height > 8000) {
  503.     static const char *const uncached[4] = {
  504.         "@", "@X", "@F", "@C"
  505.     };
  506.  
  507.     pputs(s, uncached[encode]);
  508.     op = imagestr;
  509.     strcpy(endstr, "\n");
  510.     } else {
  511.     static const char *const cached[4] = {
  512.         "$", "$X", "$F", "$C"
  513.     };
  514.  
  515.     index = image_cache_lookup(pdev, id, width_bits, height, true);
  516.     sprintf(str, "/%d%c", index / 26, index % 26 + 'A');
  517.     pputs(s, str);
  518.     if (depth != 1)
  519.         pprintld1(s, " %ld", ((width_bits + 7) >> 3) * (ulong) height);
  520.     op = cached[encode];
  521.     sprintf(endstr, "\n%s\n", imagestr);
  522.     }
  523.     /*
  524.      * In principle, we should put %%BeginData: / %%EndData around all data
  525.      * sections.  However, as long as the data are ASCII (not binary), they
  526.      * can't cause problems for a DSC parser as long as all lines are
  527.      * limited to 255 characters and there is no possibility that %% might
  528.      * occur at the beginning of a line.  ASCIIHexEncoded data can't contain
  529.      * % at all, and our implementation of ASCII85Encode also guarantees
  530.      * the desired property.  Therefore, we only bracket binary data.
  531.      */
  532.     if (encode & 1) {
  533.     /* We're using ASCII encoding. */
  534.     pputc(s, '\n');
  535.     code = psw_put_image(pdev, op, encode, data, data_x, raster,
  536.                  width, height, depth);
  537.     if (code < 0)
  538.         return code;
  539.     } else {
  540.     /*
  541.      * Do a pre-pass to compute the amount of binary data for the
  542.      * %%BeginData DSC comment.
  543.      */
  544.     stream poss;
  545.  
  546.     swrite_position_only(&poss);
  547.     pdev->strm = &poss;
  548.     code = psw_put_image(pdev, op, encode, data, data_x, raster,
  549.                  width, height, depth);
  550.     pdev->strm = s;
  551.     if (code < 0)
  552.         return code;
  553.     pprintld1(s, "\n%%%%BeginData: %ld\n", stell(&poss));
  554.     code = psw_put_image(pdev, op, encode, data, data_x, raster,
  555.                  width, height, depth);
  556.     if (code < 0)
  557.         return code;
  558.     pputs(s, "\n%%EndData");
  559.     }
  560.     pputs(s, endstr);
  561.     return 0;
  562. }
  563.  
  564. /* Print a matrix. */
  565. private void
  566. psw_put_matrix(stream * s, const gs_matrix * pmat)
  567. {
  568.     pprintg6(s, "[%g %g %g %g %g %g]",
  569.          pmat->xx, pmat->xy, pmat->yx, pmat->yy, pmat->tx, pmat->ty);
  570. }
  571.  
  572. /* ---------------- Vector device implementation ---------------- */
  573.  
  574. private int
  575. psw_beginpage(gx_device_vector * vdev)
  576. {
  577.     stream *s = vdev->strm;
  578.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  579.  
  580.     if (pdev->first_page)
  581.     psw_begin_file(pdev, NULL);
  582.     psw_write_page_header(s, (gx_device *)vdev, &pdev->pswrite_common, true);
  583.     return 0;
  584. }
  585.  
  586. private int
  587. psw_setcolors(gx_device_vector * vdev, const gx_drawing_color * pdc)
  588. {
  589.     if (!gx_dc_is_pure(pdc))
  590.     return_error(gs_error_rangecheck);
  591.     /* PostScript only keeps track of a single color. */
  592.     vdev->fill_color = *pdc;
  593.     vdev->stroke_color = *pdc;
  594.     {
  595.     stream *s = gdev_vector_stream(vdev);
  596.     gx_color_index color = gx_dc_pure_color(pdc);
  597.     int r = color >> 16;
  598.     int g = (color >> 8) & 0xff;
  599.     int b = color & 0xff;
  600.  
  601.     if (r == g && g == b) {
  602.         if (r == 0)
  603.         pputs(s, "K\n");
  604.         else
  605.         pprintd1(s, "%d G\n", r);
  606.     } else if (r == g)
  607.         pprintd2(s, "%d %d r6\n", b, r);
  608.     else if (g == b)
  609.         pprintd2(s, "%d %d r3\n", r, g);
  610.     else if (r == b)
  611.         pprintd2(s, "%d %d r5\n", g, b);
  612.     else
  613.         pprintd3(s, "%d %d %d rG\n", r, g, b);
  614.     }
  615.     return 0;
  616. }
  617.  
  618. /* Redefine dorect to recognize rectangle fills. */
  619. private int
  620. psw_dorect(gx_device_vector * vdev, fixed x0, fixed y0, fixed x1, fixed y1,
  621.        gx_path_type_t type)
  622. {
  623.     if ((type & ~gx_path_type_rule) != gx_path_type_fill)
  624.     return psdf_dorect(vdev, x0, y0, x1, y1, type);
  625.     pprintg4(gdev_vector_stream(vdev), "%g %g %g %g rf\n",
  626.          fixed2float(x0), fixed2float(y0),
  627.          fixed2float(x1 - x0), fixed2float(y1 - y0));
  628.     return 0;
  629. }
  630.  
  631. /*
  632.  * We redefine path tracing to use a compact form for polygons; also,
  633.  * we only need to write coordinates with 2 decimals of precision,
  634.  * since this is 10 times more precise than any existing output device.
  635.  */
  636. inline private double
  637. round_coord2(floatp v)
  638. {
  639.     return floor(v * 100 + 0.5) / 100.0;
  640. }
  641. private void
  642. print_coord2(stream * s, floatp x, floatp y, const char *str)
  643. {
  644.     pprintg2(s, "%g %g ", round_coord2(x), round_coord2(y));
  645.     if (str != 0)
  646.     pputs(s, str);
  647. }
  648.  
  649. private int
  650. psw_beginpath(gx_device_vector * vdev, gx_path_type_t type)
  651. {
  652.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  653.  
  654.     pdev->path_state.num_points = 0;
  655.     pdev->path_state.move = 0;
  656.     if (type & gx_path_type_clip) {
  657.     /*
  658.      * This approach doesn't work for clip + fill or stroke, but that
  659.      * combination can't occur.
  660.      */
  661.     stream *s = gdev_vector_stream(vdev);
  662.  
  663.     pputs(s, "Q q\n");
  664.     gdev_vector_reset(vdev);
  665.     }
  666.     return 0;
  667. }
  668.  
  669. private int
  670. psw_moveto(gx_device_vector * vdev, floatp x0, floatp y0, floatp x, floatp y,
  671.        gx_path_type_t type)
  672. {
  673.     stream *s = gdev_vector_stream(vdev);
  674.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  675.  
  676.     if (pdev->path_state.num_points > pdev->path_state.move)
  677.     pputs(s, (pdev->path_state.move ? "P\n" : "p\n"));
  678.     else if (pdev->path_state.move) {
  679.     /*
  680.      * Two consecutive movetos -- possible only if a zero-length line
  681.      * was discarded.
  682.      */
  683.     pputs(s, "pop pop\n");
  684.     }
  685.     print_coord2(s, x, y, NULL);
  686.     pdev->path_state.num_points = 1;
  687.     pdev->path_state.move = 1;
  688.     return 0;
  689. }
  690.  
  691. private int
  692. psw_lineto(gx_device_vector * vdev, floatp x0, floatp y0, floatp x, floatp y,
  693.        gx_path_type_t type)
  694. {
  695.     double dx = x - x0, dy = y - y0;
  696.  
  697.     /*
  698.      * Omit null lines when filling.
  699.      ****** MAYBE WRONG IF PATH CONSISTS ONLY OF NULL LINES. ******
  700.      */
  701.     if (dx != 0 || dy != 0) {
  702.     stream *s = gdev_vector_stream(vdev);
  703.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  704.  
  705.     if (pdev->path_state.num_points > 0 &&
  706.         !(pdev->path_state.num_points & 7)
  707.         )
  708.         pputc(s, '\n');    /* limit line length for DSC compliance */
  709.     if (pdev->path_state.num_points - pdev->path_state.move >= 2 &&
  710.         dx == -pdev->path_state.dprev[1].x &&
  711.         dy == -pdev->path_state.dprev[1].y
  712.         )
  713.         pputs(s, "^ ");
  714.     else
  715.         print_coord2(s, dx, dy, NULL);
  716.     pdev->path_state.num_points++;
  717.     pdev->path_state.dprev[1] = pdev->path_state.dprev[0];
  718.     pdev->path_state.dprev[0].x = dx;
  719.     pdev->path_state.dprev[0].y = dy;
  720.     }
  721.     return 0;
  722. }
  723.  
  724. private int
  725. psw_curveto(gx_device_vector * vdev, floatp x0, floatp y0,
  726.         floatp x1, floatp y1, floatp x2, floatp y2, floatp x3, floatp y3,
  727.         gx_path_type_t type)
  728. {
  729.     stream *s = gdev_vector_stream(vdev);
  730.     double dx1 = x1 - x0, dy1 = y1 - y0;
  731.     double dx2 = x2 - x0, dy2 = y2 - y0;
  732.     double dx3 = x3 - x0, dy3 = y3 - y0;
  733.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  734.  
  735.     if (pdev->path_state.num_points > 0)
  736.     pputs(s, (pdev->path_state.move ?
  737.           (pdev->path_state.num_points == 1 ? "m\n" : "P\n") :
  738.           "p\n"));
  739.     if (dx1 == 0 && dy1 == 0) {
  740.     print_coord2(s, dx2, dy2, NULL);
  741.     print_coord2(s, dx3, dy3, "v\n");
  742.     } else if (x3 == x2 && y3 == y2) {
  743.     print_coord2(s, dx1, dy1, NULL);
  744.     print_coord2(s, dx2, dy2, "y\n");
  745.     } else {
  746.     print_coord2(s, dx1, dy1, NULL);
  747.     print_coord2(s, dx2, dy2, NULL);
  748.     print_coord2(s, dx3, dy3, "c\n");
  749.     }
  750.     pdev->path_state.num_points = 0;
  751.     pdev->path_state.move = 0;
  752.     return 0;
  753. }
  754.  
  755. private int
  756. psw_closepath(gx_device_vector * vdev, floatp x0, floatp y0,
  757.           floatp x_start, floatp y_start, gx_path_type_t type)
  758. {
  759.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  760.  
  761.     pputs(gdev_vector_stream(vdev),
  762.       (pdev->path_state.num_points > 0 && pdev->path_state.move ?
  763.        "H\n" : "h\n"));
  764.     pdev->path_state.num_points = 0;
  765.     pdev->path_state.move = 0;
  766.     return 0;
  767. }
  768.  
  769. private int
  770. psw_endpath(gx_device_vector * vdev, gx_path_type_t type)
  771. {
  772.     stream *s = vdev->strm;
  773.     const char *star = (type & gx_path_type_even_odd ? "*" : "");
  774.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  775.  
  776.     if (pdev->path_state.num_points > 0 && !pdev->path_state.move)
  777.     pputs(s, "p ");
  778.     if (type & gx_path_type_fill) {
  779.     if (type & (gx_path_type_stroke | gx_path_type_clip))
  780.         pprints1(s, "q f%s Q ", star);
  781.     else
  782.         pprints1(s, "f%s\n", star);
  783.     }
  784.     if (type & gx_path_type_stroke) {
  785.     if (type & gx_path_type_clip)
  786.         pputs(s, "q S Q ");
  787.     else
  788.         pputs(s, "S\n");
  789.     }
  790.     if (type & gx_path_type_clip)
  791.     pprints1(s, "Y%s\n", star);
  792.     return 0;
  793. }
  794.  
  795. /* ---------------- Driver procedures ---------------- */
  796.  
  797. /* ------ Open/close/page ------ */
  798.  
  799. /* Open the device. */
  800. private int
  801. psw_open(gx_device * dev)
  802. {
  803.     gs_memory_t *mem = gs_memory_stable(dev->memory);
  804.     gx_device_vector *const vdev = (gx_device_vector *)dev;
  805.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  806.  
  807.     vdev->v_memory = mem;
  808.     vdev->vec_procs = &psw_vector_procs;
  809.     {
  810.     int code = gdev_vector_open_file_bbox(vdev, 512, true);
  811.  
  812.     if (code < 0)
  813.         return code;
  814.     }
  815.     gdev_vector_init(vdev);
  816.     vdev->fill_options = vdev->stroke_options = gx_path_type_optimize;
  817.     pdev->first_page = true;
  818.     pdev->binary_ok = !pdev->params.ASCII85EncodePages;
  819.     pdev->image_writer = gs_alloc_struct(mem, psdf_binary_writer,
  820.                      &st_psdf_binary_writer,
  821.                      "psw_open(image_writer)");
  822.     memset(pdev->image_writer, 0, sizeof(*pdev->image_writer));  /* for GC */
  823.     image_cache_reset(pdev);
  824.     return 0;
  825. }
  826.  
  827. /* Wrap up ("output") a page. */
  828. private int
  829. psw_output_page(gx_device * dev, int num_copies, int flush)
  830. {
  831.     gx_device_vector *const vdev = (gx_device_vector *)dev;
  832.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  833.     stream *s = gdev_vector_stream(vdev);
  834.  
  835.     sflush(s);            /* sync stream and file */
  836.     psw_write_page_trailer(vdev->file, num_copies, flush);
  837.     vdev->in_page = false;
  838.     pdev->first_page = false;
  839.     gdev_vector_reset(vdev);
  840.     image_cache_reset(pdev);
  841.     if (ferror(vdev->file))
  842.     return_error(gs_error_ioerror);
  843.     return gx_finish_output_page(dev, num_copies, flush);
  844. }
  845.  
  846. /* Close the device. */
  847. /* Note that if this is being called as a result of finalization, */
  848. /* the stream may have been finalized; but the file will still be open. */
  849. private int
  850. psw_close(gx_device * dev)
  851. {
  852.     gx_device_vector *const vdev = (gx_device_vector *)dev;
  853.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  854.     FILE *f = vdev->file;
  855.     gs_rect bbox;
  856.  
  857.     gx_device_bbox_bbox(vdev->bbox_device, &bbox);
  858.     if (pdev->first_page & !vdev->in_page) {
  859.     /* Nothing has been written.  Write the file header now. */
  860.     psw_begin_file(pdev, &bbox);
  861.     } else {
  862.     /* If there is an incomplete page, complete it now. */
  863.     if (vdev->in_page) {
  864.         /*
  865.          * Flush the stream if it hasn't been flushed (and finalized)
  866.          * already.
  867.          */
  868.         stream *s = vdev->strm;
  869.  
  870.         if (s->swptr != s->cbuf - 1)
  871.         sflush(s);
  872.         psw_write_page_trailer(vdev->file, 1, 1);
  873.         dev->PageCount++;
  874.     }
  875.     }
  876.     psw_end_file(f, dev, &pdev->pswrite_common, &bbox);
  877.     gs_free_object(pdev->v_memory, pdev->image_writer,
  878.            "psw_close(image_writer)");
  879.     pdev->image_writer = 0;
  880.     return gdev_vector_close_file(vdev);
  881. }
  882.  
  883. /* ---------------- Get/put parameters ---------------- */
  884.  
  885. /* Get parameters. */
  886. private int
  887. psw_get_params(gx_device * dev, gs_param_list * plist)
  888. {
  889.     gx_device_pswrite *const pdev = (gx_device_pswrite *)dev;
  890.     int code = gdev_psdf_get_params(dev, plist);
  891.     int ecode;
  892.  
  893.     if (code < 0)
  894.     return code;
  895.     if ((ecode = param_write_float(plist, "LanguageLevel", &pdev->pswrite_common.LanguageLevel)) < 0)
  896.     return ecode;
  897.     return code;
  898. }
  899.  
  900. /* Put parameters. */
  901. private int
  902. psw_put_params(gx_device * dev, gs_param_list * plist)
  903. {
  904.     int ecode = 0;
  905.     int code;
  906.     gs_param_name param_name;
  907.     gx_device_pswrite *const pdev = (gx_device_pswrite *)dev;
  908.     float ll = pdev->pswrite_common.LanguageLevel;
  909.     psdf_version save_version = pdev->version;
  910.  
  911.     switch (code = param_read_float(plist, (param_name = "LanguageLevel"), &ll)) {
  912.     case 0:
  913.         if (ll == 1.0 || ll == 1.5 || ll == 2.0)
  914.         break;
  915.         code = gs_error_rangecheck;
  916.     default:
  917.         ecode = code;
  918.         param_signal_error(plist, param_name, ecode);
  919.     case 1:
  920.         ;
  921.     }
  922.  
  923.     if (ecode < 0)
  924.     return ecode;
  925.     /*
  926.      * We have to set version to the new value, because the set of
  927.      * legal parameter values for psdf_put_params varies according to
  928.      * the version.
  929.      */
  930.     {
  931.     static const psdf_version vv[3] =
  932.     {
  933.         psdf_version_level1, psdf_version_level1_color,
  934.         psdf_version_level2
  935.     };
  936.  
  937.     pdev->version = vv[(int)(ll * 2) - 2];
  938.     }
  939.     code = gdev_psdf_put_params(dev, plist);
  940.     if (code < 0) {
  941.     pdev->version = save_version;
  942.     return code;
  943.     }
  944.     pdev->pswrite_common.LanguageLevel = ll;
  945.     return code;
  946. }
  947.  
  948. /* ---------------- Images ---------------- */
  949.  
  950. /* Copy a monochrome bitmap. */
  951. private int
  952. psw_copy_mono(gx_device * dev, const byte * data,
  953.     int data_x, int raster, gx_bitmap_id id, int x, int y, int w, int h,
  954.           gx_color_index zero, gx_color_index one)
  955. {
  956.     gx_device_vector *const vdev = (gx_device_vector *)dev;
  957.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  958.     gx_drawing_color color;
  959.     const char *op;
  960.     int code = 0;
  961.  
  962.     if (w <= 0 || h <= 0)
  963.     return 0;
  964.     (*dev_proc(vdev->bbox_device, copy_mono))
  965.     ((gx_device *) vdev->bbox_device, data, data_x, raster, id,
  966.      x, y, w, h, zero, one);
  967.     if (one == gx_no_color_index) {
  968.     color_set_pure(&color, zero);
  969.     code = gdev_vector_update_fill_color((gx_device_vector *) pdev,
  970.                          &color);
  971.     op = "If";
  972.     } else if (zero == vdev->black && one == vdev->white)
  973.     op = "1 I";
  974.     else {
  975.     if (zero != gx_no_color_index) {
  976.         code = (*dev_proc(dev, fill_rectangle)) (dev, x, y, w, h, zero);
  977.         if (code < 0)
  978.         return code;
  979.     }
  980.     color_set_pure(&color, one);
  981.     code = gdev_vector_update_fill_color((gx_device_vector *) pdev,
  982.                          &color);
  983.     op = ",";
  984.     }
  985.     if (code < 0)
  986.     return 0;
  987.     code = gdev_vector_update_clip_path(vdev, NULL);
  988.     if (code < 0)
  989.     return code;
  990.     return psw_image_write(pdev, op, data, data_x, raster, id,
  991.                x, y, w, h, 1);
  992. }
  993.  
  994. /* Copy a color bitmap. */
  995. private int
  996. psw_copy_color(gx_device * dev,
  997.            const byte * data, int data_x, int raster, gx_bitmap_id id,
  998.            int x, int y, int w, int h)
  999. {
  1000.     int depth = dev->color_info.depth;
  1001.     const byte *bits = data + data_x * 3;
  1002.     char op[6];
  1003.     int code;
  1004.     gx_device_vector *const vdev = (gx_device_vector *)dev;
  1005.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  1006.  
  1007.     if (w <= 0 || h <= 0)
  1008.     return 0;
  1009.     (*dev_proc(vdev->bbox_device, copy_color))
  1010.     ((gx_device *) vdev->bbox_device, data, data_x, raster, id,
  1011.      x, y, w, h);
  1012.     /*
  1013.      * If this is a 1-pixel-high image, check for it being all the
  1014.      * same color, and if so, fill it as a rectangle.
  1015.      */
  1016.     if (h == 1 && !memcmp(bits, bits + 3, (w - 1) * 3)) {
  1017.     return (*dev_proc(dev, fill_rectangle))
  1018.         (dev, x, y, w, h, (bits[0] << 16) + (bits[1] << 8) + bits[2]);
  1019.     }
  1020.     sprintf(op, "%d Ic", depth / 3);    /* RGB */
  1021.     code = gdev_vector_update_clip_path(vdev, NULL);
  1022.     if (code < 0)
  1023.     return code;
  1024.     return psw_image_write(pdev, op, data, data_x, raster, id,
  1025.                x, y, w, h, depth);
  1026. }
  1027.  
  1028. /* Fill or stroke a path. */
  1029. /* We redefine these to skip empty paths, and to allow optimization. */
  1030. private int
  1031. psw_fill_path(gx_device * dev, const gs_imager_state * pis,
  1032.           gx_path * ppath, const gx_fill_params * params,
  1033.           const gx_device_color * pdevc, const gx_clip_path * pcpath)
  1034. {
  1035.     if (gx_path_is_void(ppath))
  1036.     return 0;
  1037.     /* Update the clipping path now. */
  1038.     gdev_vector_update_clip_path((gx_device_vector *)dev, pcpath);
  1039.     return gdev_vector_fill_path(dev, pis, ppath, params, pdevc, pcpath);
  1040. }
  1041. private int
  1042. psw_stroke_path(gx_device * dev, const gs_imager_state * pis,
  1043.         gx_path * ppath, const gx_stroke_params * params,
  1044.         const gx_device_color * pdcolor, const gx_clip_path * pcpath)
  1045. {
  1046.     gx_device_vector *const vdev = (gx_device_vector *)dev;
  1047.  
  1048.     if (gx_path_is_void(ppath) &&
  1049.     (gx_path_is_null(ppath) ||
  1050.      gs_currentlinecap((const gs_state *)pis) != gs_cap_round)
  1051.     )
  1052.     return 0;
  1053.     /* Update the clipping path now. */
  1054.     gdev_vector_update_clip_path(vdev, pcpath);
  1055.     /* Do the right thing for oddly transformed coordinate systems.... */
  1056.     {
  1057.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  1058.     stream *s;
  1059.     int code;
  1060.     double scale;
  1061.     bool set_ctm;
  1062.     gs_matrix mat;
  1063.  
  1064.     if (!gx_dc_is_pure(pdcolor))
  1065.         return gx_default_stroke_path(dev, pis, ppath, params, pdcolor,
  1066.                       pcpath);
  1067.     set_ctm = (bool)gdev_vector_stroke_scaling(vdev, pis, &scale, &mat);
  1068.     gdev_vector_update_clip_path(vdev, pcpath);
  1069.     gdev_vector_prepare_stroke((gx_device_vector *)pdev, pis, params,
  1070.                    pdcolor, scale);
  1071.     s = pdev->strm;
  1072.     if (set_ctm) {
  1073.         pputs(s, "q");
  1074.         if (is_fzero2(mat.xy, mat.yx) && is_fzero2(mat.tx, mat.ty))
  1075.         pprintg2(s, " %g %g scale\n", mat.xx, mat.yy);
  1076.         else {
  1077.         psw_put_matrix(s, &mat);
  1078.         pputs(s, "concat\n");
  1079.         }
  1080.     }
  1081.     code = gdev_vector_dopath(vdev, ppath, gx_path_type_stroke,
  1082.                   (set_ctm ? &mat : (const gs_matrix *)0));
  1083.     if (code < 0)
  1084.         return code;
  1085.     if (set_ctm)
  1086.         pputs(s, "Q\n");
  1087.     }
  1088.     /* We must merge in the bounding box explicitly. */
  1089.     return (vdev->bbox_device == 0 ? 0 :
  1090.         dev_proc(vdev->bbox_device, stroke_path)
  1091.           ((gx_device *)vdev->bbox_device, pis, ppath, params,
  1092.            pdcolor, pcpath));
  1093. }
  1094.  
  1095. /* Fill a mask. */
  1096. private int
  1097. psw_fill_mask(gx_device * dev,
  1098.           const byte * data, int data_x, int raster, gx_bitmap_id id,
  1099.           int x, int y, int w, int h,
  1100.           const gx_drawing_color * pdcolor, int depth,
  1101.           gs_logical_operation_t lop, const gx_clip_path * pcpath)
  1102. {
  1103.     gx_device_vector *const vdev = (gx_device_vector *)dev;
  1104.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  1105.  
  1106.     if (w <= 0 || h <= 0)
  1107.     return 0;
  1108.     if (depth > 1 ||
  1109.     gdev_vector_update_fill_color(vdev, pdcolor) < 0 ||
  1110.     gdev_vector_update_clip_path(vdev, pcpath) < 0 ||
  1111.     gdev_vector_update_log_op(vdev, lop) < 0
  1112.     )
  1113.     return gx_default_fill_mask(dev, data, data_x, raster, id,
  1114.                     x, y, w, h, pdcolor, depth, lop, pcpath);
  1115.     (*dev_proc(vdev->bbox_device, fill_mask))
  1116.     ((gx_device *) vdev->bbox_device, data, data_x, raster, id,
  1117.      x, y, w, h, pdcolor, depth, lop, pcpath);
  1118.     /* Update the clipping path now. */
  1119.     gdev_vector_update_clip_path(vdev, pcpath);
  1120.     return psw_image_write(pdev, ",", data, data_x, raster, id,
  1121.                x, y, w, h, 1);
  1122. }
  1123.  
  1124. /* ---------------- High-level images ---------------- */
  1125.  
  1126. private image_enum_proc_plane_data(psw_image_plane_data);
  1127. private image_enum_proc_end_image(psw_image_end_image);
  1128. private const gx_image_enum_procs_t psw_image_enum_procs = {
  1129.     psw_image_plane_data, psw_image_end_image
  1130. };
  1131.  
  1132. /* Start processing an image. */
  1133. private int
  1134. psw_begin_image(gx_device * dev,
  1135.         const gs_imager_state * pis, const gs_image_t * pim,
  1136.         gs_image_format_t format, const gs_int_rect * prect,
  1137.           const gx_drawing_color * pdcolor, const gx_clip_path * pcpath,
  1138.         gs_memory_t * mem, gx_image_enum_common_t ** pinfo)
  1139. {
  1140.     gx_device_vector *const vdev = (gx_device_vector *)dev;
  1141.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  1142.     gdev_vector_image_enum_t *pie =
  1143.     gs_alloc_struct(mem, gdev_vector_image_enum_t,
  1144.             &st_vector_image_enum, "psw_begin_image");
  1145.     const gs_color_space *pcs = pim->ColorSpace;
  1146.     const gs_color_space *pbcs = pcs;
  1147.     const char *base_name;
  1148.     gs_color_space_index index;
  1149.     int num_components;
  1150.     bool binary = pdev->binary_ok;
  1151.     byte *buffer = 0;        /* image buffer if needed */
  1152.     stream *bs = 0;        /* buffer stream if needed */
  1153. #define MAX_IMAGE_OP 10        /* imagemask\n */
  1154.     int code;
  1155.  
  1156.     if (pie == 0)
  1157.     return_error(gs_error_VMerror);
  1158.     if (prect && !(prect->p.x == 0 && prect->p.y == 0 &&
  1159.            prect->q.x == pim->Width && prect->q.y == pim->Height)
  1160.     )
  1161.     goto fail;
  1162.     switch (pim->format) {
  1163.     case gs_image_format_chunky:
  1164.     case gs_image_format_component_planar:
  1165.     break;
  1166.     default:
  1167.     goto fail;
  1168.     }
  1169.     pie->memory = mem;
  1170.     pie->default_info = 0;    /* not used */
  1171.     if (pim->ImageMask) {
  1172.     index = -1;        /* bogus, not used */
  1173.     num_components = 1;
  1174.     } else {
  1175.     index = gs_color_space_get_index(pcs);
  1176.     num_components = gs_color_space_num_components(pcs);
  1177.     if (pim->CombineWithColor)
  1178.         goto fail;
  1179.     /*
  1180.      * We can only handle Device color spaces right now, or Indexed
  1181.      * color spaces over them, and only the default Decode [0 1 ...]
  1182.      * or [0 2^BPC-1] respectively.
  1183.      */
  1184.     switch (index) {
  1185.     case gs_color_space_index_Indexed: {
  1186.         if (pdev->pswrite_common.LanguageLevel < 2 || pcs->params.indexed.use_proc ||
  1187.         pim->Decode[0] != 0 ||
  1188.         pim->Decode[1] != (1 << pim->BitsPerComponent) - 1
  1189.         ) {
  1190.         goto fail;
  1191.         }
  1192.         pbcs = (const gs_color_space *)&pcs->params.indexed.base_space;
  1193.         switch (gs_color_space_get_index(pbcs)) {
  1194.         case gs_color_space_index_DeviceGray:
  1195.         base_name = "DeviceGray"; break;
  1196.         case gs_color_space_index_DeviceRGB:
  1197.         base_name = "DeviceRGB"; break;
  1198.         case gs_color_space_index_DeviceCMYK:
  1199.         base_name = "DeviceCMYK"; break;
  1200.         default:
  1201.         goto fail;
  1202.         }
  1203.         break;
  1204.     }
  1205.     case gs_color_space_index_DeviceGray:
  1206.     case gs_color_space_index_DeviceRGB:
  1207.     case gs_color_space_index_DeviceCMYK: {
  1208.         int i;
  1209.  
  1210.         for (i = 0; i < num_components * 2; ++i)
  1211.         if (pim->Decode[i] != (i & 1))
  1212.             goto fail;
  1213.         break;
  1214.     }
  1215.     default:
  1216.         goto fail;
  1217.     }
  1218.     }
  1219.     if (pdev->pswrite_common.LanguageLevel < 2 && !pim->ImageMask) {
  1220.     /*
  1221.      * Restrict ourselves to Level 1 images: bits per component <= 8,
  1222.      * not indexed.
  1223.      */
  1224.     if (pim->BitsPerComponent > 8 || pbcs != pcs)
  1225.         goto fail;
  1226.     }
  1227.     if (gdev_vector_begin_image(vdev, pis, pim, format, prect, pdcolor,
  1228.                 pcpath, mem, &psw_image_enum_procs, pie) < 0)
  1229.     goto fail;
  1230.     if (binary) {
  1231.     /*
  1232.      * We need to buffer the entire image in memory.  Currently, the
  1233.      * only reason for this is the infamous "short image" problem: the
  1234.      * image may actually have fewer rows than its height specifies.  If
  1235.      * it weren't for that, we could know the size of the binary data in
  1236.      * advance.  However, this will change if we compress images.
  1237.      */
  1238.     uint bsize = MAX_IMAGE_OP +
  1239.         ((pie->bits_per_row + 7) >> 3) * pie->height;
  1240.  
  1241.     buffer = gs_alloc_bytes(mem, bsize, "psw_begin_image(buffer)");
  1242.     bs = s_alloc(mem, "psw_begin_image(buffer stream)");
  1243.     if (buffer && bs) {
  1244.         swrite_string(bs, buffer, bsize);
  1245.     } else {
  1246.         /* An allocation failed. */
  1247.         gs_free_object(mem, bs, "psw_begin_image(buffer stream)");
  1248.         gs_free_object(mem, buffer, "psw_begin_image(buffer)");
  1249.         /*
  1250.          * Rather than returning VMerror, we fall back to an ASCII
  1251.          * encoding, which doesn't require a buffer stream.
  1252.          */
  1253.         buffer = 0;
  1254.         bs = 0;
  1255.         binary = false;
  1256.     }
  1257.     }
  1258.     if (binary) {
  1259.     /* Set up the image stream to write into the buffer. */
  1260.     stream *save = pdev->strm;
  1261.  
  1262.     pdev->strm = bs;
  1263.     code = psw_image_stream_setup(pdev, true);
  1264.     pdev->strm = save;
  1265.     } else {
  1266.     code = psw_image_stream_setup(pdev, false);
  1267.     }
  1268.     if (code < 0)
  1269.     goto fail;
  1270.     /* Update the clipping path now. */
  1271.     gdev_vector_update_clip_path(vdev, pcpath);
  1272.     /* Write the image/colorimage/imagemask preamble. */
  1273.     {
  1274.     stream *s = gdev_vector_stream((gx_device_vector *) pdev);
  1275.     const char *source = (code ? "@X" : "@");
  1276.     gs_matrix imat;
  1277.     const char *op;
  1278.  
  1279.     pputs(s, "q");
  1280.     (*dev_proc(dev, get_initial_matrix)) (dev, &imat);
  1281.     gs_matrix_scale(&imat, 72.0 / dev->HWResolution[0],
  1282.             72.0 / dev->HWResolution[1], &imat);
  1283.     gs_matrix_invert(&imat, &imat);
  1284.     gs_matrix_multiply(&ctm_only(pis), &imat, &imat);
  1285.     psw_put_matrix(s, &imat);
  1286.     pprintd2(s, "concat\n%d %d ", pie->width, pie->height);
  1287.     if (pim->ImageMask) {
  1288.         pputs(s, (pim->Decode[0] == 0 ? "false" : "true"));
  1289.         psw_put_matrix(s, &pim->ImageMatrix);
  1290.         pputs(s, source);
  1291.         op = "imagemask";
  1292.     } else {
  1293.         pprintd1(s, "%d", pim->BitsPerComponent);
  1294.         psw_put_matrix(s, &pim->ImageMatrix);
  1295.         if (pbcs != pcs) {
  1296.         /* This is an Indexed color space. */
  1297.         pprints1(s, "[/Indexed /%s ", base_name);
  1298.         pprintd1(s, "%d\n", pcs->params.indexed.hival);
  1299.         /*
  1300.          * Don't write the table in binary: it might interfere
  1301.          * with DSC parsing.
  1302.          */
  1303.         s_write_ps_string(s, pcs->params.indexed.lookup.table.data,
  1304.                   pcs->params.indexed.lookup.table.size,
  1305.                   PRINT_ASCII85_OK);
  1306.         pprintd1(s, "\n]setcolorspace[0 %d]", (int)pim->Decode[1]);
  1307.         pprints2(s, "%s %s",
  1308.              (pim->Interpolate ? "true" : "false"), source);
  1309.         op = "IC";
  1310.         } else if (index == gs_color_space_index_DeviceGray) {
  1311.         pputs(s, source);
  1312.         op = "image";
  1313.         } else {
  1314.         if (format == gs_image_format_chunky)
  1315.             pprints1(s, "%s false", source);
  1316.         else {
  1317.             /* We have to use procedures. */
  1318.             pputs(s, source);
  1319.             pprintd2(s, " %d %d B",
  1320.                  (pim->Width * pim->BitsPerComponent + 7) >> 3,
  1321.                  num_components);
  1322.         }
  1323.         pprintd1(s, " %d", num_components);
  1324.         op = "colorimage";
  1325.         }
  1326.     }
  1327.     pputc(s, '\n');
  1328.     pprints1((bs ? bs : s), "%s\n", op);
  1329.     }
  1330.     *pinfo = (gx_image_enum_common_t *) pie;
  1331.     return 0;
  1332.  fail:
  1333.     gs_free_object(mem, bs, "psw_begin_image(buffer stream)");
  1334.     gs_free_object(mem, buffer, "psw_begin_image(buffer)");
  1335.     gs_free_object(mem, pie, "psw_begin_image");
  1336.     return gx_default_begin_image(dev, pis, pim, format, prect,
  1337.                   pdcolor, pcpath, mem, pinfo);
  1338. }
  1339.  
  1340. /* Process the next piece of an image. */
  1341. private int
  1342. psw_image_plane_data(gx_image_enum_common_t * info,
  1343.              const gx_image_plane_t * planes, int height,
  1344.              int *rows_used)
  1345. {
  1346.     gx_device *dev = info->dev;
  1347.     gx_device_pswrite *const pdev = (gx_device_pswrite *)dev;
  1348.     gdev_vector_image_enum_t *pie = (gdev_vector_image_enum_t *) info;
  1349.     int code =
  1350.     gx_image_plane_data_rows(pie->bbox_info, planes, height, rows_used);
  1351.     int pi;
  1352.  
  1353.     for (pi = 0; pi < pie->num_planes; ++pi) {
  1354.     if (pie->bits_per_row != pie->width * info->plane_depths[pi])
  1355.         return_error(gs_error_rangecheck);
  1356.     psw_put_bits(pdev->image_stream, planes[pi].data,
  1357.              planes[pi].data_x * info->plane_depths[pi],
  1358.              planes[pi].raster, pie->bits_per_row,
  1359.              *rows_used);
  1360.     }
  1361.     pie->y += *rows_used;
  1362.     return code;
  1363. }
  1364.  
  1365. /* Clean up by releasing the buffers. */
  1366. private int
  1367. psw_image_end_image(gx_image_enum_common_t * info, bool draw_last)
  1368. {
  1369.     gx_device *dev = info->dev;
  1370.     gx_device_vector *const vdev = (gx_device_vector *)dev;
  1371.     gx_device_pswrite *const pdev = (gx_device_pswrite *)vdev;
  1372.     gdev_vector_image_enum_t *pie = (gdev_vector_image_enum_t *) info;
  1373.     int code;
  1374.  
  1375.     code = gdev_vector_end_image(vdev, pie, draw_last, pdev->white);
  1376.     if (code > 0) {
  1377.     stream *s = pdev->strm;
  1378.     stream *bs = pdev->image_stream;
  1379.  
  1380.     /* If we were buffering a binary image, write it now. */
  1381.     while (bs != s && bs->strm != 0)
  1382.         bs = bs->strm;
  1383.     psw_image_cleanup(pdev);
  1384.     if (bs != s) {
  1385.         /*
  1386.          * We were buffering a binary image.  Write it now, with the
  1387.          * DSC comments.
  1388.          */
  1389.         gs_memory_t *mem = bs->memory;
  1390.         byte *buffer = bs->cbuf;
  1391.         long len = stell(bs);
  1392.         uint ignore;
  1393.  
  1394.         pprintld1(s, "%%%%BeginData: %ld\n", len);
  1395.         sputs(s, buffer, (uint)len, &ignore);
  1396.         pputs(s, "\n%%EndData");
  1397.         /* Free the buffer and its stream. */
  1398.         gs_free_object(mem, bs, "psw_image_end_image(buffer stream)");
  1399.         gs_free_object(mem, buffer, "psw_image_end_image(buffer)");
  1400.     }
  1401.     pputs(s, "\nQ\n");
  1402.     }
  1403.     return code;
  1404. }
  1405.